﻿using IOA.MES.Business;
using IOA.MES.DataAccess.VModel;
using IOA.MES.EsbApi.Models.Response;
using IOA.MES.EsbApi.Models.Request;
using IOA.MES.EsbApi.Models.Request.Product;
using NLog;
using System.Linq;
using System.Web.Http;
using System.Collections.Generic;

namespace IOA.MES.EsbApi.Controllers
{
    /// <summary>
    /// 物料管理
    /// </summary>
    public class ProductController : ApiController
    {
        private Logger logger = LogManager.GetLogger(nameof(ProductController));

        /// <summary>
        /// 创建产品接口
        /// </summary>
        [HttpPost]
        public BaseResponse CreateProduct(BaseRequest<List<CreateProductRequest>> request)
        {
            if (request == null || request.requestInfo == null || request.requestInfo.data == null || request.requestInfo.data.list == null)
            {
                return new BaseResponse();
            }

            var validProducts = request.requestInfo.data.list.Where(_ => !string.IsNullOrWhiteSpace(_.ItemNumber)).ToList();
            var products = validProducts.Select(_ => new VProduct
            {
                ProductCode = _.ItemNumber?.Trim(),
                ProductName = _.ItemDescZhs?.Trim(),
                Specifications = _.ItemDescZhs?.Trim(),
                MainUnitName = _.PrimaryUnitOfMeasure?.Trim(),
                CategoryCode = _.CategorySets.FirstOrDefault(c => string.Equals(c.CategorySetNameZhs, "库存", System.StringComparison.CurrentCultureIgnoreCase))?.SetValue?.Trim(),
            }).ToList();

            new ProductMgr().AsyncProduct(products);
            return new BaseResponse();
        }
    }
}
